<template>
  <basic-container class="to-do-task-save">
    <el-form ref="form" :model="form" label-position="right" label-width="170px" :rules="rules">
      <h3>接入待办任务信息</h3>
      <div class="border">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="所属应用" prop="appId">
              <el-select v-model="form.appId" :disabled="!!form.id">
                <el-option v-for="(item, index) in appList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务名称" prop="accessName">
              <el-input v-model="form.accessName" :disabled="!!form.id" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接入应用集" prop="appSetId">
              <el-select v-model="form.appSetId" :disabled="!!form.id">
                <el-option v-for="(item, index) in appSetList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="接入描述" prop="describe">
              <el-input v-model="form.describe" type="textarea" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务图标">
              <el-upload
                class="avatar-uploader"
                :action="VUE_APP_BASE_API + '/file/upload'"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <div v-if="form.icon" class="avatar">
                  <TokenImg :img-url="VUE_APP_BASE_API + form.icon" style="width: 50px;height: 50px;" />
                  <!-- <img :src="VUE_APP_BASE_API + form.icon" style="width: 50px;height: 50px;"> -->
                  <div class="ml20" style="color: #0368d1;">重新上传图片</div>
                  <div class="ml20" style="color: red" @click.stop="form.icon=''">删除图片</div>
                </div>
                <div v-else class="upload-icon-box">
                  <i class="el-icon-plus avatar-uploader-icon" />
                </div>
                <p class="el-upload__tip">温馨提示： 请上传200px*200px的高清图标</p>
                <p class="el-upload__tip">（支持jpg、bmp、png、svg等格式）</p>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <h3>接入配置</h3>
      <div class="border">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="接入服务地址" prop="url">
              <el-input v-model="form.url" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="接入任务总数服务地址" prop="assist1">
              <el-input v-model="form.assist1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="接入服务订阅令牌" prop="token">
              <el-input v-model="form.token" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限码" prop="authCode">
              <el-input v-model="form.authCode" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="不可使用权限码：" prop="noAuthCode">
              <el-input v-model="form.noAuthCode" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <h3>显示配置</h3>
      <div class="border">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="显示样式" prop="displayStyle" label-width="100px">
              <el-select v-model="form.displayStyle" @change="displayStyleChange">
                <el-option v-for="(item, index) in styleList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <div>
              <BuiltIn :style-enums="styleEnums" :current-type="form.displayStyle" />
            </div>
          </el-col>
          <el-col :span="18">
            <YituTable
              :loading="false"
              :table-obj="tableObj"
              :data="form.configList"
              border
              @changeTableValue="changeTableValue"
            />
            <div class="btn-group">
              <el-button v-loading="loading" type="primary" @click="saveData">确定</el-button>
              <el-button @click="$router.go(-1)">取消</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <CropperImgDialog
      ref="cropper"
      title="裁剪图片"
      :visible.sync="visible"
      :cropper-file="{original: originalImg}"
      :confirm="handleCroppedConfirm"
    />
  </basic-container>
</template>
<script>

import { getById, getDisplayStyle, edit, app, appSet } from '@/api/accessManagement/todotask'
import BuiltIn from './components/BuiltIn.vue'
import { getToken } from '@/util/auth'
import CropperImgDialog from '@/components/CropperImgDialog/index.vue'
import TokenImg from '@/components/common/TokenImg.vue'
export default {
  name: 'ToDoTaskSave',
  components: {
    BuiltIn,
    TokenImg,
    CropperImgDialog
  },
  data() {
    return {
      visible: false,
      originalImg: '',
      form: {
        accessName: '', // 任务名称
        appId: null, // 所属应用ID
        // appStr: '', // 所属应用名称
        appSetId: null, // 所属应用集id
        // appSetStr: '', // 所属应用集名称
        assist1: '', // 接入任务总数服务地址
        authCode: '', // 权限码
        noAuthCode: '', // 不可使用权限码
        configList: [
          {
            fieldName: '', // 字段名称
            cnName: '', // 中文名称
            alias: '', // 中文别名
            config: '', // 样式枚举值
            fieldConfigId: '', // 公共字段配置表ID
            id: '', // 接入业务显示配置ID
            sampleData: '' // 示例数据
          }
        ],
        describe: '', // 接入描述
        displayStyle: 1, // 显示样式
        icon: '', // 图标地址
        id: '', // 应用及模块接入id
        token: '', // 接入服务订阅令牌
        url: '' // 接入服务地址
      },
      styleList: [], // 显示样式列表
      tableObj: {
        tableHead: [
          { label: '字段名称', value: 'fieldName' },
          { label: '中文名称', value: 'cnName' },
          { label: '中文别名', value: 'alias', editType: 'input' },
          { label: '显示配置', value: 'config', editType: 'select', options: [] },
          { label: '示例数据', value: 'sampleData', editType: 'input' }
        ],
        isSelection: false,
        isHasIndex: false,
        hasHandle: false,
        isEditTable: true
      },
      styleEnums: [], // 选择显示样式后构建而成的数据
      headers: {
        Token: getToken()
      },
      appSetList: [], // 应用集列表
      appList: [], // 所属应用列表
      loading: false,
      rules: {
        appId: [
          { required: true, message: '请选择所属应用', trigger: 'change' }
        ],
        accessName: [
          { required: true, message: '请填写任务名称', trigger: 'blur' }
        ],
        appSetId: [
          { required: true, message: '请选择接入应用集', trigger: 'change' }
        ],
        url: [
          { required: true, message: '请输入接入服务地址', trigger: 'blur' }
        ],
        assist1: [
          { required: true, message: '请输入接入任务总数服务地址', trigger: 'blur' }
        ],
        token: [
          { required: true, message: '请输入接入服务订阅令牌', trigger: 'blur' }
        ],
        displayStyle: [
          { required: true, message: '请选择显示样式', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    }
  },
  created() {
    this.getEnums()
    Promise.all([this.getDisplayStyleEnum(), this.getDetail()]).then(res => {
      this.styleList = res[0].map(item => ({
        label: item.name,
        value: item.value,
        styleEnums: item.styleEnums
      }))
      for (const key in res[1]) {
        if (key === 'displayStyle') {
          this.$set(this.form, key, res[1][key] || 1)
        } else {
          this.$set(this.form, key, res[1][key])
        }
      }
      this.setStyleEnums()
      this.setFieldConfigOptions()
    })
  },
  methods: {
    getEnums() {
      // 任务标签
      appSet({}).then(res => {
        const data = res.data.data
        this.appSetList = data.map(item => ({
          label: item.appname,
          value: item.appid
        }))
      })
      // 所属系统
      app({ }).then(res => {
        const data = res.data.data
        this.appList = data.map(item => ({
          label: item.appname,
          value: item.appid
        }))
      })
    },
    setFieldConfigOptions() {
      console.log(this.form.configList)
      const options = this.styleList.find(item => item.value === this.form.displayStyle).styleEnums.map(item => {
        const obj = {
          label: item.desc,
          value: item.value,
          disabled: this.form.configList.some(itemChildren => itemChildren.config === item.value)
        }
        return obj
      })
      this.$set(this.tableObj.tableHead[3], 'options', options)
    },
    setStyleEnums() {
      this.styleEnums = this.styleList.find(item => item.value === (this.form.displayStyle || 1)).styleEnums.map(item => {
        const obj = this.form.configList.find(itemChildren => itemChildren.config === item.value)
        if (obj) {
          // item.alias = obj.alias || obj.cnName
          item.alias = obj.alias
          item.fieldName = obj.fieldName
          item.sampleData = obj.sampleData
          item.label = obj.desc
        } else {
          item.alias = ''
          item.fieldName = ''
          item.sampleData = ''
        }
        return item
      })
    },
    getDisplayStyleEnum() {
      return new Promise((resolve, reject) => {
        getDisplayStyle({}).then(res => {
          const data = res.data.data
          resolve(data)
        })
      })
    },
    getDetail() {
      return new Promise((resolve, reject) => {
        getById({ id: this.$route.query.id || 0 }).then(res => {
          const data = res.data.data
          resolve(data)
        })
      })
    },
    // 保存待办任务数据
    saveData() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const { accessName, appId, appSetId, assist1, authCode, noAuthCode, configList, describe, displayStyle, icon, id, token, url } = this.form
          if (appId === appSetId) {
            this.$message.warning('应用集不能接入自己本身')
            return
          }
          if (this.tableObj.tableHead[3].options.some(item => !item.disabled)) {
            this.$message.warning('显示配置列必须要按照所选的显示样式，选满选项')
            return
          }
          const params = {
            accessName,
            appId,
            appSetId,
            assist1,
            authCode,
            noAuthCode,
            configDTOList: configList.map(item => ({
              alias: item.alias,
              config: item.config,
              fieldConfigId: item.fieldConfigId,
              id: item.id,
              sampleData: item.sampleData
            })),
            describe,
            displayStyle,
            icon,
            id,
            token,
            url
          }
          this.loading = true
          edit(params).then(res => {
            this.$message.success('保存成功')
            this.$router.replace({ name: '任务中心接入', params: { isRefresh: true }})
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    // 显示样式改变事件
    displayStyleChange(val) {
      this.setStyleEnums()
      this.setFieldConfigOptions()
    },
    // 表格内容改变事件
    changeTableValue(index, key, value) {
      if (key === 'config') {
        this.setFieldConfigOptions()
        this.setStyleEnums()
      } else if (['alias', 'sampleData'].includes(key)) {
        this.setStyleEnums()
      }
    },
    beforeAvatarUpload(file) {
      const imgReg = /\.(jpg|bmp|png|svg)$/
      const maxSize = 5 * 1024 * 1024
      console.log({ file })
      const { name, size } = file
      let errorMsg = ''
      if (!imgReg.test(name.toLowerCase())) {
        errorMsg = '图片支持jpg、bmp、png、svg格式'
      } else if (maxSize < size) {
        errorMsg = '文件大小不能超过5M'
      }
      if (errorMsg) {
        this.$message.warning(errorMsg)
      }
      return !errorMsg
    },
    handleAvatarSuccess(res, file) {
      this.originalImg = res.data || ''
      this.visible = true
    },
    handleCroppedConfirm(res) {
      this.form.icon = res.data
    }
  }
}
</script>
<style lang="scss">
.to-do-task-save{
  p{
    margin: 0;
    line-height: normal;
  }
  .el-input, .el-select{
    width: 100%;
  }
  .upload-icon-box{
    line-height: auto;
    .upload-icon{
      width: 200px;
      height: 200px;
      box-sizing: border-box;
      line-height: 200px;
      border: 1px dashed #d9d9d9;
      i{
        font-size: 28px;
      }
    }
  }
  .avatar-uploader{
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    padding: 10px 0;
  }
  .avatar-uploader:hover{
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 270px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .el-upload__tip{
    margin-top: 7px;
  }
  .avatar{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .border{
    border: 1px solid #eee;
    padding: 10px;
  }
  .btn-group{
    text-align: center;
    margin-top: 10px;
  }
  .table{
    .el-form-item{
      margin-bottom: 0;
    }
  }
}
</style>
